/*
 * @Author: kenter.zheng
 * @Date: 2019-08-07 11:19:22
 * @Last Modified by: kenter.zheng
 * @Last Modified time: 2020-10-21 06:56:23
 */
import axios from 'axios'
import { environment } from '@/models/environment'
import store from '@/script/store'

import { getItem, signOut, setItem } from './common';
import { service } from '../api/get-data';
import ElementUI from 'element-ui'

const instance = axios.create({
  baseURL: environment.API_URL,
  timeout: 300000
})

let requestList = [];
let refreshTokenLock = 0;
let lastTime = 0;

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
  console.log("config:", config)
  // conswwei  {
  // 在发送请求之前做些什么
  // return Promise.reject(config)
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
  console.log("response:", response)
  // 对响应数据做点什么
  return response
}, function (error) {
  if (error.response) {
    if (error.response.status === 405) {
      let config = error.config;
      const nowTime = +Date.now();
      if (nowTime > refreshTokenLock + 1000) {
        refreshTokenLock = nowTime;
        return getRefreshToken().then((res) => {
          if (res && res.data) {
            setItem('token', res.data);
            config.headers = config.headers || {};
            config.headers.authorization = res.data.token || {};
          }
          requestList.forEach(cb => cb(res.data.token))
          requestList = []
          return instance(config)
        }).catch(() => {
          // signOut();
        }).finally(() => {
          refreshTokenLock = 0;
        })
      } else {
        // 正在刷新token，将返回一个未执行resolve的promise
        return new Promise((resolve) => {
          // 将resolve放进队列，用一个函数形式来保存，等token刷新后直接执行
          requestList.push((token) => {
            config.headers['authorization'] = token
            resolve(instance(config))
          })
        })
      }
    } else if (error.response.status === 403) {
      const nowTime = +Date.now();
      if (nowTime > lastTime + 2000) {
        lastTime = nowTime;
        ElementUI.Message.error('登录信息过期，请重新登录');
      }
      store.commit('closeLoading')
      // signOut();
      return new Promise((resolve, reject) => {
      })
    } else {
  
    }
  }
  
  // 对响应错误做点什么
  return Promise.reject(error)
})

const request = (routeJson, params) => {
  if (params && params.closeLoading) {
    delete params.closeLoading;
  } else {
    store.commit('openLoading');
  }
  let method = routeJson.method;
  let url = routeJson.url;
  let config = {
    url: url,
    method: method,
  };

  let user = getItem('user');
  let token = getItem('token');

  if (user) {
    config.headers = config.headers || {};
    config.headers.user = user.SysUserId;
    config.headers.purview = (user.PurviewGroupIds || []).join(',');
  }
  if (token) {
    config.headers = config.headers || {};
    config.headers.authorization = token.token || {};
  }

  if (method === 'get') {
    config = { ...config, params: params };
  } else {
    config = { ...config, data: params };
  }

  return new Promise((resolve, reject) => {
    instance.request(config).then(response => {
      if (response && response.status === 200) {
        let _body = response.data;
        if (_body.code != 0) {
          // ElementUI.Message.error(_body.message);
          return reject(_body);
        } else {
          return resolve(_body);
        }
      } else {
        return reject(response.data);
      }
    }).catch(error => {
      return reject(error);
    }).finally(() => {
      store.commit('closeLoading')
    });
  })
}

const getRefreshToken = () => {
  let token = getItem('token');
  return service.refreshToken({ refreshToken: token.refreshToken });
}

export default {
  request,
  instance
}
